import axios from 'axios'
import router from '../routes'
//封装axios请求
//设置请求接口的超时时间
let http = axios.create({
    timeout:60000,
    withCredentials: true
})
//设置post,put请求的content-type
http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
http.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded'
//axios.defaults.headers.common['Authorization'] = sessionStorage.getItem('Authorization')
//添加请求拦截器
http.interceptors.request.use(config=>{
    if(config.method === 'get'){
        //get请求直接时间戳
        let symbol = config.url.indexOf('?')>=0?'&':'?'
        config.url+=symbol + '_='+Date.now()
    }
    //请求发送前进行处理
    return config
},error=>{
    //请求错误处理
    return Promise.reject(error)
})
//添加响应拦截器
http.interceptors.response.use(response=>{
    let {data} = response;
    console.log(data);
    return data
},error=>{
    let info = {}
    let {data} = error.response;
    console.log(data);
    //未登录或者token失效请求拦截,路由跳转
    if( data.code == 4009 ||
        data.code == 4001 ||
        data.code == 4002 ||
        data.code == 4003 ||
        data.code == 4004 ||
        data.code == 4005 ||
        data.code == 4006 ||
        data.code == 4007 ||
        data.code == 5001
    ){
        router.replace({path:'/login'});
    }
    if(!error.response){
        info={
            code:5000,
            msg:'NetWork Error'
        }
    }else{
        //整理错误信息格式
        info={
            code:data.code,
            data:data,
            msg:data.msg
        }
    }
    return Promise.reject(info)
})
/**
 * 创建统一封装过的axios实例
 * @return {AxiosInstance}
 * */
export default function(){
    return http
}